package sfeir.ergosum.tools;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;

import android.net.Uri;

import sfeir.ergosum.model.Person;

public class MicroformatDomParser {

    private String weburl;

    public MicroformatDomParser(String url) {
        this.weburl = url;
    }

    public Person getPerson() {

        String response = "";
        String requestUrl = weburl;
        String name = weburl.substring(0, weburl.lastIndexOf('.')).replace('.', ' ');
        if (weburl.endsWith(".tel")) {
            requestUrl = "http://pilot.webproxy.nic.tel/vcard.action?domain=" + weburl;
        }
        else if (weburl.contains(ErgoSumParser.URL)) {
            requestUrl = weburl;
            name = Uri.parse(weburl).getLastPathSegment();
        }
        else if (!weburl.endsWith(".vcard") && !weburl.endsWith(".vcf"))
            requestUrl = "http://technorati.com/contacts/contact/?url=" + weburl;

        try {
            URLConnection connection = new URL(requestUrl).openConnection();
            response = IOUtils.toString(connection.getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
//            throw e;
        }

        if (response == null || !response.startsWith("BEGIN:VCARD") || !response.contains("END:VCARD")) {
            return null;
        }

        return VCardParser.parse(response, name);
    }
}
